package com.sysphysic.aiotsystem.service;

import com.sysphysic.aiotsystem.config.SimpleMqttConfig;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

@Slf4j
@Service
public class PahoMqttService {

    @Autowired
    private SimpleMqttConfig mqttConfig;

    private MqttClient mqttClient;

    @PostConstruct
    public void init() {
        connectMqtt();
    }

    private void connectMqtt() {
        try {
            MemoryPersistence persistence = new MemoryPersistence();
            mqttClient = new MqttClient(
                    mqttConfig.getBrokerUrl(),
                    mqttConfig.getClientId(),
                    persistence
            );

            MqttConnectOptions connOpts = new MqttConnectOptions();
            connOpts.setCleanSession(true);
            connOpts.setUserName(mqttConfig.getUsername());
            connOpts.setPassword(mqttConfig.getPassword().toCharArray());
            connOpts.setConnectionTimeout(10);
            connOpts.setKeepAliveInterval(60);
            connOpts.setAutomaticReconnect(true);

            log.info("连接到MQTT Broker: {}", mqttConfig.getBrokerUrl());
            mqttClient.connect(connOpts);
            log.info("MQTT连接成功");

        } catch (MqttException e) {
            log.error("MQTT连接失败: {}", e.getMessage());
        }
    }

    public boolean sendControlMessage(String device, String action) {
        if (mqttClient == null || !mqttClient.isConnected()) {
            log.error("MQTT客户端未连接");
            // 尝试重连
            connectMqtt();
            return false;
        }

        try {
            String payload = String.format("{\"device\":\"%s\",\"action\":\"%s\"}", device, action);
            MqttMessage message = new MqttMessage(payload.getBytes());
            message.setQos(0);
            message.setRetained(false);

            mqttClient.publish(mqttConfig.getControlTopic(), message);
            log.info("MQTT消息发送成功 - 设备: {}, 动作: {}, 主题: {}",
                    device, action, mqttConfig.getControlTopic());
            return true;

        } catch (MqttException e) {
            log.error("MQTT消息发送失败: {}", e.getMessage());
            return false;
        }
    }

    public void controlLed(String color, String action) {
        sendControlMessage("led_" + color, action);
    }

    @PreDestroy
    public void cleanup() {
        if (mqttClient != null && mqttClient.isConnected()) {
            try {
                mqttClient.disconnect();
                mqttClient.close();
                log.info("MQTT连接已关闭");
            } catch (MqttException e) {
                log.error("关闭MQTT连接时出错: {}", e.getMessage());
            }
        }
    }

    public boolean isConnected() {
        return mqttClient != null && mqttClient.isConnected();
    }
}